'use strict';

angular.module('fbdApp.auxModule')

.factory('fbdService', function($http, $q, $filter) {
  return {
    test: function(url, postData) {

      var req = {
        method: 'POST',
        url: url,
        data: postData

      };

      var deferred = $q.defer();

      $http(req).success(function(res) {
        deferred.resolve(res);
        // console.log(res);
      }).error(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    },

    save: function(url, addData) {

      var req = {
        method: 'POST',
        url: url,
        data: addData
      };
      var deferred = $q.defer();

      $http(req).success(function(res) {
        deferred.resolve(res);
        // console.log(res);
      }).error(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    },

    testRule: function(url, postData) {
      var req = {
        method: 'POST',
        url: url,
        data: postData

      };

      var deferred = $q.defer();

      $http(req).success(function(res) {
        var testResult = {};
        testResult.data = res.result;
        // testResult.info = '共有' + res.result.length +
        //   '条记录';
        testResult.rule = res.rule;
        if (postData.text.type == 'file') {
          testResult.highlightText = '';
        } else {
          testResult.highlightText =
            '<hr /><label>在原文中位置：</label><br />' +
            $filter('highlightFilter')(res.result,
              postData.text.content);
        }
        if (res.result.length) {
          testResult.info = '共有' + res.result.length + '条记录';
        } else {
          testResult.info = '无任何结果，请重新修改规则';
          testResult.highlightText = '';
        }
        deferred.resolve(testResult);
        // deferred.resolve(res);
        // console.log(res);
      }).error(function(err) {
        var testResult = {};
        testResult.info = err + '，请重新发送请求';
        testResult.data = [];
        testResult.highlightText = '';
        deferred.reject(testResult);
      });
      return deferred.promise;
    },

    testTpl: function(url, postData) {
      var req = {
        method: 'POST',
        url: url,
        data: postData
      };
      var tplName = postData.template.name;
      var deferred = $q.defer();
      $http(req).success(function(res) {
        var testResult = {};
        testResult.data = res[tplName];
        // testResult.info = '共有' + res[tplName].length + '篇文章合格';
        if (res[tplName].length) {
          testResult.info = '共有' + res[tplName].length + '篇合格文章';
        } else {
          testResult.info = '无任何结果，请重新修改字段';
        }
        deferred.resolve(testResult);
      }).error(function(err) {
        var testResult = {};
        testResult.info = err + '，请重新发送请求';
        testResult.data = [];
        deferred.reject(testResult);
      });
      return deferred.promise;
    }
  };
});
